﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 信息模板管理
    /// </summary>
     [OutputCache(Duration = 0, VaryByParam = "none")]
    public class SysTemplateController : AdminBaseController
    {

        /// <summary>
        /// 信息模板管理
        /// </summary>
        /// <returns>返回信息模板管理页面视图</returns>
        [AuthorityActionFilter("m_SysTemplate", Order = 1)]
        [LogPageActionFilter("信息模板管理", Order = 2)]
        public ActionResult Index(string focusNodeName="")
        {
            ViewData["focusNodeName"] = focusNodeName;
            return View();
        }

        // <summary>
        /// html模板预览
        /// </summary>
        /// <param name="temID"></param>
        /// <returns></returns>
        public ActionResult HtmlTemplateRead(decimal temID)
        {
            BLL.SysTemplate temBll = new BLL.SysTemplate();
            ViewData["content"] =  temBll.GetContent(temID);
            return View();
        }

        /// <summary>
        /// office模板预览
        /// </summary>
        /// <param name="temID"></param>
        /// <returns></returns>
        public ActionResult OfficeTemplateRead(decimal temID)
        {
            BLL.SysTemplate temBll = new BLL.SysTemplate();
            string url = temBll.GetFileName(temID);
            ViewData["url"] = url;
            ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
            ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);
            return View();
        }

        /// <summary>
        /// office模板
        /// </summary>
        /// <param name="temClsID"></param>
        /// <param name="temType"></param>
        /// <param name="temID"></param>
        /// <returns></returns>
        public ActionResult OfficeTemplate(string temClsID, string temType, decimal temID = 0)
        {
            string title = string.Empty;
            string url = string.Empty;
            string newOfficeType = string.Empty;
            string FIsDefault = "";
            if (temID != 0)
            {
                BLL.SysTemplate temBll = new BLL.SysTemplate();
                Model.SysTemplate temObj = temBll.GetModel(temID);
                title = temObj.FTitle;
                url = temObj.FFileName;
                FIsDefault = temObj.FIsDefault;
            }

            switch (temType)
            {
                case "W": newOfficeType = "1"; break;
                case "E": newOfficeType = "2"; break;
                case "P": newOfficeType = "3"; break;
            }

            ViewData["url"] = url;
            ViewData["newOfficeType"] = newOfficeType;
            ViewData["title"] = title;
            ViewData["fSourceNo"] = temClsID;
            ViewData["temID"] = temID;
            ViewData["temType"] = temType;
            if (FIsDefault == "Y")
            {
                ViewData["FIsDefault"] = true;
            }
            else
            {
                ViewData["FIsDefault"] = false;
            }
            ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
            ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);

            return View();
        }

        /// <summary>
        /// 模板删除同时删除相关文件
        /// </summary>
        /// <param name="temID"></param>
        /// <returns></returns>
        public string DelTemplate(decimal temID)
        {
            BLL.SysTemplate temBll = new BLL.SysTemplate();
            Model.SysTemplate temOBj = temBll.GetModel(temID);
            if (null != temOBj)
            {
                string filePath = temOBj.FTemplateType != "H" ? temOBj.FFileName : string.Empty;

                try
                {
                    temBll.Delete(temID);
                    if (filePath != string.Empty)
                    {
                        GenerateUtil.DeleteFile(filePath);
                    }
                    return "ok";
                }
                catch (Exception)
                {
                    return "error";
                }
            }
            else
            {
                return "数据不存在";
            }
        }


        /// <summary>
        /// 批量删除类别和模板
        /// </summary>
        /// <param name="temModalJson"></param>
        /// <returns></returns>
        [HttpPost]
        public string DelMany(string idList)
        {
            try
            {
                BLL.SysTemplate SysTemplateBLL = new BLL.SysTemplate();
                SysTemplateBLL.DeleteList(idList);
                return "ok";
            }
            catch
            {
                return "error";
            }
        }



        /// <summary>
        /// Office模板保存
        /// </summary>
        [HttpPost]
        public void OfficeTemplateSave()
        {

            System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
            if (uploadFiles.Count == 0)
            {
                Response.Write("error|无上传文件");
                Response.Flush();
                Response.End();
                return;
            }


            string officeType = string.Empty;
            switch (Request.Form["FTemplateType"])
            {
                case "W": officeType = ".doc"; break;
                case "E": officeType = ".xls"; break;
                case "P": officeType = ".ppt"; break;
            }

            BLL.SysTemplate temBll = new BLL.SysTemplate();
            Model.SysTemplate temObj = new Model.SysTemplate();
            temObj.FTemplateCls = "DOC";
            string oldFileName = string.Empty;
            decimal temID = 0;
            decimal.TryParse(Request.Form["FTemplateID"], out temID);
            if (temID == 0)//增加
            {
                SetTemObj(temObj);
            }
            else
            {
                temObj = temBll.GetModel(temID);
                if (null == temObj)
                {
                    temID = 0;
                    temObj = new Model.SysTemplate();
                    SetTemObj(temObj);
                }
                else
                {
                    oldFileName = temObj.FFileName;
                }
                string fIsDefault = Request.Form["FIsDefault"];
                if (fIsDefault == "C")
                {
                    temObj.FIsDefault = "Y";
                }
                else
                {
                    temObj.FIsDefault = "N";
                }
            }

            temObj.FTitle = Request.Form["FTitle"].Trim();

            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string fileSavePath = System.Configuration.ConfigurationManager.AppSettings["FileSavePath"] + "TemplateFiles/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + deptNo;
            GenerateUtil.Addfolder(fileSavePath);


            System.Web.HttpPostedFileBase theFile = uploadFiles[0];
            string fileName = GenerateUtil.GenerateStringId() + "_" + temObj.FTitle.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", "");
            temObj.FFileName = fileSavePath + "/" + fileName + officeType;
            bool fileSave = false;
            string returnValue = string.Empty;
            try
            {
                theFile.SaveAs(Server.MapPath(temObj.FFileName));
                fileSave = true;

                if (temID == 0)//增加
                {
                    temBll.Add(temObj);
                    returnValue = "add";
                }
                else
                {
                    temBll.Update(temObj);
                    returnValue = temObj.FTitle;
                    GenerateUtil.DeleteFile(oldFileName);
                }

                Response.Write("ok|" + returnValue);
                Response.Flush();
                Response.End();


            }
            catch (Exception)
            {
                if (fileSave)
                {
                    GenerateUtil.DeleteFile(temObj.FFileName);
                }

                Response.Write("error|模板文件保存失败");
                Response.Flush();
                Response.End();
            }


        }

        private void SetTemObj(Model.SysTemplate temObj)
        {
            temObj.FEntityNo = GlobalConstant.ENTITYNO;
            temObj.FTemplateType = "O";
            temObj.FSourceNo = Request.Form["FSourceNo"];
            string fIsDefault = Request.Form["FIsDefault"];
            if (fIsDefault == "C")
            {
                temObj.FIsDefault = "Y";
            }
            else
            {
                temObj.FIsDefault = "N";
            }
        }

        /// <summary>
        /// HTML模板保存
        /// </summary>
        /// <param name="model"></param>
        [HttpPost]
        [ValidateInput(false)]
        public void HtmlTemplateSave(Model.SysTemplate model)
        {
            model.FEntityNo = GlobalConstant.ENTITYNO;
            model.FTemplateType = "H";
            model.FTemplateCls = "DOC";
            model.FTitle = model.FTitle.Trim();
            model.FSourceNo = Request.Form["FSourceNo"];
            model.FContent = System.Text.Encoding.Default.GetBytes(Fetch.Post("fFContent"));
            if (model.FIsDefault == "True")
            {
                model.FIsDefault = "Y";
            }
            else
            {
                model.FIsDefault = "N";
            }

            BLL.SysTemplate temBll = new BLL.SysTemplate();
            if (model.FTemplateID == 0)//增加
            {
                try
                {
                    temBll.Add(model);
                    Response.Write("<script>alert(\"保存成功\");if (window.opener != null) {window.opener.createHtmlOK();}window.close();</script>");
                    Response.Flush();
                    Response.End();
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('html模板创建失败');window.location.href= rootPath + '/Admin/DocManager/HtmlTemplate?temClsID=" + (null == model.FSourceNo ? "0" : model.FSourceNo) + "';</script>");
                    Response.Flush();
                    Response.End();
                }
            }
            else
            {
                try
                {
                    temBll.Update(model);
                    Response.Write("<script>alert(\"保存成功\");if (window.opener != null) {window.opener.createHtmlEditOK('" + model.FTitle + "');}window.close();</script>");
                    Response.Flush();
                    Response.End();
                }
                catch (Exception)
                {
                    Response.Write("<script>alert('html模板创建失败');window.location.href= rootPath + '/Admin/DocManager/HtmlTemplate?temClsID=" + (null == model.FSourceNo ? "0" : model.FSourceNo) + "&temID=" + model.FTemplateID + "';</script>");
                    Response.Flush();
                    Response.End();
                }
            }

        }


        /// <summary>
        /// html模板
        /// </summary>
        /// <param name="temClsID"></param>
        /// <param name="temID"></param>
        /// <returns></returns>
        public ActionResult HtmlTemplate(string temClsID, decimal temID = 0)
        {
            Model.SysTemplate temObj = new Model.SysTemplate();
            if (temID != 0)//修改
            {
                BLL.SysTemplate temBll = new BLL.SysTemplate();
                temObj = temBll.GetModel(temID);
                if (null == temObj)
                {
                    temObj = new Model.SysTemplate();
                    temObj.FSourceNo = temClsID;
                }
            }
            else
            {
                temObj.FSourceNo = temClsID;
            }


            return View(temObj);
        }


        public ActionResult LeftTree(string focusNodeName = "")
        {
            string focusNodeID = "";
            BLL.DocCls docClsBll = new BLL.DocCls();
            List<Model.DocCls> DocClsList = docClsBll.GetListByEntityNo(GlobalConstant.ENTITYNO);
            TreeItemModel treeRootItemModel = new TreeItemModel(null)
            {
                Id = "docList",
                Name = "信息分类"
            };


            TreeModelList treeModelList = new TreeModelList();
            List<Model.DocCls> SelectDocClsList = (from nm in DocClsList where nm.FPreDocClsCd == "" select nm).ToList();


            foreach (Model.DocCls row in SelectDocClsList)
            {

                TreeItemModel treeParentItemModel = new TreeItemModel(treeRootItemModel)
                {
                    Id = Url.Action("TemplateList", "SysTemplate", new { clscd = row.FDocClsCd, type = row.FEditMode }),
                    Name = row.FDocClsName
                };

                LoadTreeNode(treeParentItemModel, row.FDocClsCd, DocClsList, ref focusNodeID, focusNodeName );
                if (row.FDocClsCd == focusNodeName)
                {
                    focusNodeID = treeParentItemModel.Id;
                }
            }
            treeModelList.Add(treeRootItemModel);
            ViewData["focusNodeName"] = focusNodeID;
            return View(treeModelList);
        }
         
        /// <summary>
        /// 记载信息类别
        /// </summary>
        /// <param name="node">父级树节点</param>
        /// <param name="fDocClsCd">类别编号</param>
        private void LoadTreeNode(TreeItemModel node, string fDocClsCd, List<Model.DocCls> docClsList,ref string focusNodeID,string focusNodeName )
        {
            List<Model.DocCls> SelectDocClsList = (from nm in docClsList where nm.FPreDocClsCd == fDocClsCd select nm).ToList();
            foreach (Model.DocCls model in SelectDocClsList)
            {
                TreeItemModel treeParentItemModel = new TreeItemModel(node)
                {

                    Id = Url.Action("TemplateList", "SysTemplate", new { clscd = model.FDocClsCd, type = model.FEditMode }), //"TemplateList?clscd=" + model.FDocClsCd + "&&type=" + model.FEditMode,
                    Name = model.FDocClsName
                };
                if (model.FDocClsCd == focusNodeName)
                {
                    focusNodeID = treeParentItemModel.Id;
                }

                LoadTreeNode(treeParentItemModel, model.FDocClsCd, docClsList, ref focusNodeID, focusNodeName);

            }
        }

        public ActionResult TemplateList(string clscd, string type)
        {
            BLL.SysTemplate SysTemplateBLL = new BLL.SysTemplate();
            List<Model.SysTemplate> SysTemplateList = SysTemplateBLL.GetModelList(" FEntityNo = '" + Common.GlobalConstant.ENTITYNO + "' and FSourceNo = '" + clscd + "'");
            ViewData["templateClsID"] = clscd;

            ViewData["ShowWEP"] = type;
            return View(SysTemplateList);
        }
    }
}
